package com.example.basic.exception;

import com.example.basic.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


/**
 * ClassName: GlobalExceptionHandler
 * Description:
 * date: 2021/12/14 9:56
 * author zesion lee
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception exception) {
        logError(request, exception.getMessage());
        return Result.error(65550, exception.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException exception) {
        logError(request, exception.getMessage());
        return Result.error(65551, exception.getMessage());
    }


    @ExceptionHandler(MyCustomException.class)
    public Result handleCustomException(HttpServletRequest request, MyCustomException exception) {
        logError(request, exception.getMsg());
        return Result.error(exception.getCode(), exception.getMsg());
    }


    private void logError(HttpServletRequest request, String msg) {
        log.info("调用接口 {} 出错，错误信息：{}", request.getRequestURI(), msg);
    }
}
